<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form class="antd-modal-form" v-bind="formItemLayout" ref="formRef" name="ConversionSituationTableForm">
          <a-row>
<!--						<a-col :span="12">
							<a-form-item label="成果id" v-bind="validateInfos.achievementId" id="ConversionSituationTable-achievementId" name="achievementId">
								<a-input v-model:value="formData.achievementId" placeholder="请输入成果id"  allow-clear ></a-input>
							</a-form-item>
						</a-col>-->
						<a-col :span="12">
							<a-form-item label="成果名称" v-bind="validateInfos.achievementName" id="ConversionSituationTable-achievementName" name="achievementName">
								<a-input v-model:value="formData.achievementName" placeholder="请输入成果名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="来源课题类型 （国家、省、科技部、集团xxx项目/自选）" v-bind="validateInfos.sourceType" id="ConversionSituationTable-sourceType" name="sourceType">
								<a-input v-model:value="formData.sourceType" placeholder="请输入来源课题类型 （国家、省、科技部、集团xxx项目/自选）"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="完成单位" v-bind="validateInfos.completionOrg" id="ConversionSituationTable-completionOrg" name="completionOrg">
								<a-input v-model:value="formData.completionOrg" placeholder="请输入完成单位"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="主要完成人" v-bind="validateInfos.completionPersonnel" id="ConversionSituationTable-completionPersonnel" name="completionPersonnel">
								<a-input v-model:value="formData.completionPersonnel" placeholder="请输入主要完成人"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="鉴定部门" v-bind="validateInfos.appraisalOrg" id="ConversionSituationTable-appraisalOrg" name="appraisalOrg">
								<a-input v-model:value="formData.appraisalOrg" placeholder="请输入鉴定部门"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="鉴定等级 （审定等级、国内外领先、专利类型）" v-bind="validateInfos.appraisalLevel" id="ConversionSituationTable-appraisalLevel" name="appraisalLevel">
								<j-dict-select-tag v-model:value="formData.appraisalLevel" dictCode="appraisal_level" placeholder="请选择鉴定等级 （审定等级、国内外领先、专利类型）"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="是否获得植物新品种保护权（已获得填写获得时间）" v-bind="validateInfos.obtainProtection" id="ConversionSituationTable-obtainProtection" name="obtainProtection">
								<a-input v-model:value="formData.obtainProtection" placeholder="请输入是否获得植物新品种保护权（已获得填写获得时间）"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="转化时间" v-bind="validateInfos.transformTime" id="ConversionSituationTable-transformTime" name="transformTime">
								<a-input v-model:value="formData.transformTime" placeholder="请输入转化时间"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="转化方式" v-bind="validateInfos.transformMethod" id="ConversionSituationTable-transformMethod" name="transformMethod">
								<a-input v-model:value="formData.transformMethod" placeholder="请输入转化方式"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="是否为本年度合同" v-bind="validateInfos.isAnnualContract" id="ConversionSituationTable-isAnnualContract" name="isAnnualContract">
								<j-dict-select-tag type='radio' v-model:value="formData.isAnnualContract" dictCode="is_annual_contract" placeholder="请选择是否为本年度合同"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="转化合同金额（万元）" v-bind="validateInfos.conversionContractAmount" id="ConversionSituationTable-conversionContractAmount" name="conversionContractAmount">
								<a-input-number v-model:value="formData.conversionContractAmount" placeholder="请输入转化合同金额（万元）" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="实际到账金额（万元）" v-bind="validateInfos.actualAmount" id="ConversionSituationTable-actualAmount" name="actualAmount">
								<a-input-number v-model:value="formData.actualAmount" placeholder="请输入实际到账金额（万元）" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="转化至单位名称" v-bind="validateInfos.convertToUnitName" id="ConversionSituationTable-convertToUnitName" name="convertToUnitName">
								<a-input v-model:value="formData.convertToUnitName" placeholder="请输入转化至单位名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="推广应用情况" v-bind="validateInfos.promotionApplicationSituation" id="ConversionSituationTable-promotionApplicationSituation" name="promotionApplicationSituation">
								<a-input v-model:value="formData.promotionApplicationSituation" placeholder="请输入推广应用情况"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, onMounted, inject, defineProps, unref } from 'vue';
  import { defHttp } from '/jeecgboot-vue3/src/utils/http/axios';
  import { useMessage } from '/jeecgboot-vue3/src/hooks/web/useMessage';
  import JDictSelectTag from '/jeecgboot-vue3/src/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { getValueType } from '/jeecgboot-vue3/src/utils';
  import { conversionSituationTableSaveOrUpdate } from '../SummaryOfProject.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/jeecgboot-vue3/src/components/Form/src/container/JFormContainer.vue';

  //接收主表id
  const mainId = inject('mainId');
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
        achievementId: '',   
        achievementName: '',   
        sourceType: '',   
        completionOrg: '',   
        completionPersonnel: '',   
        appraisalOrg: '',   
        appraisalLevel: undefined,
        obtainProtection: '',   
        transformTime: '',   
        transformMethod: '',   
        isAnnualContract: undefined,
        conversionContractAmount: undefined,
        actualAmount: undefined,
        convertToUnitName: '',   
        promotionApplicationSituation: '',   
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
  const props = defineProps({
    disabled: { type: Boolean, default: false },
  });
  const formItemLayout = {
    labelCol: { xs: { span: 24 }, sm: { span: 5 } },
    wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },
  };
  
  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData,tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
   
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    if (unref(mainId)) {
      model['projectId'] = unref(mainId);
    }
    await conversionSituationTableSaveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
